/*
 *  Copyright (C) 2011  Clint Priest
 *
 *  This file is part of pklib.
 *
 *  pklib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  pklib is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with pklib.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Portions borrowed or re-written from prototype
 */
 
/* Array Reference */
var ar = Array;

Object.extend(ar.prototype, {
	find: function(func) {
		for(var i=0; i < this.length; i++) {
			if(func(this[i]) == true)
				return this[i];
		}
		return null;
	},
	uniq: function() {
		var results = [ ];
		this.forEach( function(elem) {
			if(results.indexOf(elem) == -1)
				results.push(elem);
		} );
		return results;
	},
	invoke: function(method) {
		var args = $A(arguments).slice(1);
		return this.map(function(value) {
			return value[method].apply(value, args);
		});
	},
	pluck: function(property) {
		var results = [];
		this.forEach(function(value) {
			results.push(value[property]);
		});
		return results;
	},
	last: function() {
		if(this.length > 0)
			return this[this.length-1];
	},
	flatten: function() {
		return this.reduce(function(array, value) {
			if (Object.isArray(value))
				return array.concat(value.flatten());
			array.push(value);
			return array;
		}, []);
	}
} );

/* Converts an iterable element to an array */
function $A(iterable) {
	if (!iterable) return [];
	if ('toArray' in Object(iterable)) return iterable.toArray();
	var length = iterable.length || 0, results = new Array(length);
	while (length--) results[length] = iterable[length];
	return results;
}